package com.example.mumu.passwordbook.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;

import com.example.mumu.passwordbook.domain.Account;
import com.example.mumu.passwordbook.domain.IconEnum;
import com.example.mumu.passwordbook.domain.TypeEnum;

import java.util.ArrayList;
import java.util.List;

public class AccountDao {

    private Context context;
    private AccountDBOpenHelper dbOpenHelper;
    private SQLiteDatabase db;

    public AccountDao(Context context) {
        this.context = context;
        this.dbOpenHelper = new AccountDBOpenHelper(context);
        this.db = dbOpenHelper.getWritableDatabase();
    }

    public void insert(Account account) {
        db.execSQL("insert into account(name,icon,type,username,password,remark) values(?,?,?,?,?,?)",
                new Object[]{account.getName(), account.getIcon().toString(), account.getType().toString(),
                        account.getUsername(), account.getPassword(), account.getRemark()});
    }

    public List<Account> selectByType(TypeEnum type) {
        Cursor cursor;
        if (type != null) {
            cursor = db.rawQuery("select * from account where type = ?", new String[]{type.toString()});
        } else {
            cursor = db.rawQuery("select * from account", null);
        }

        return getAccountList(cursor);
    }


    public List<Account> selectByNameAndType(String name, TypeEnum type) {

        Cursor cursor;
        if (type == null) {
            cursor = db.rawQuery("select * from account where name like ?", new String[]{"%" + name});
        } else {
            cursor = db.rawQuery("select * from account where name like ? and type = ?", new String[]{"%" + name, type.toString()});
        }
        return getAccountList(cursor);
    }


    @NonNull
    private List<Account> getAccountList(Cursor cursor) {
        List<Account> list = new ArrayList<>();
        //存在数据才返回true
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String iconStr = cursor.getString(cursor.getColumnIndex("icon"));
            String typeStr = cursor.getString(cursor.getColumnIndex("type"));
            String username = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            String remark = cursor.getString(cursor.getColumnIndex("remark"));

            list.add(new Account(id, IconEnum.valueOf(iconStr), TypeEnum.valueOf(typeStr), name, username, password, remark));
        }
        cursor.close();
        return list;
    }

    public void delete(int id) {
        db.execSQL("delete from account where id = ?",new Integer[]{id});
    }
}
